import { Deduplication } from "./Deduplication";
/**
 *
 * @param code 数学代码
 * @param language 数学语言
 * @param container 元素容器
 * @param stylecssrules 样式规则
 */
export default async function rendermathjax(
    code: string,
    language: "latex" | "mathml" | "asciimath",
    container: HTMLElement,
    stylecssrules: Set<string>
) {
    const { rendermath, initmathjax } = await import(
        "@masx200/mathjax-module-async"
    );
    const mathjax = await initmathjax();
    // console.log(mathjax);

    const opts = mathjax.getMetricsFor(document.body);
    // console.log(opts);
    mathjax.startup.document.addStyleSheet();
    //@ts-ignore
    await rendermath(code, language, opts).then((html) => {
        container.innerHTML = html;
    });
    //@ts-ignore
    const chtmlStylesheet = mathjax.chtmlStylesheet() as HTMLStyleElement;
    // console.log(chtmlStylesheet.sheet);
    const mathjaxstyle: HTMLStyleElement | null = document.getElementById(
        chtmlStylesheet.id
    ) as HTMLStyleElement | null;
    const sheet = mathjaxstyle?.sheet;
    if (sheet) {
        // console.log(sheet);
        const cssRules = sheet?.cssRules || [];

        Deduplication(
            Array.from(cssRules).map((r) => {
                return r.cssText;
            })
        ).forEach((rule) => {
            stylecssrules.add(rule);
        });
    } else {
        throw Error("no style sheet");
    }
    document.getElementById(chtmlStylesheet.id)?.remove();
}
